import {
    AlipayCircleOutlined,
    LockOutlined,
    MobileOutlined,
    TaobaoCircleOutlined,
    UserOutlined,
    WeiboCircleOutlined,
} from '@ant-design/icons';
import {Alert, Space, message, Tabs} from 'antd';
import React, {useState} from 'react';
import ProForm, {ProFormCaptcha, ProFormCheckbox, ProFormText} from '@ant-design/pro-form';
import {useIntl, Link, history, FormattedMessage, SelectLang, useModel} from 'umi';
import Footer from '@/components/Footer';
import {login} from '@/services/ant-design-pro/api';
import {getFakeCaptcha} from '@/services/ant-design-pro/login';

import styles from './index.less';
import {adminLogin, getMenus} from "@/services/bz/bz-api";
import defaultSettings from "../../../../config/defaultSettings";

const LoginMessage: React.FC<{
    content: string;
}> = ({content}) => (
    <Alert
        style={{
            marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
    />
);

/** 此方法会跳转到 redirect 参数所在的位置 */
const goto = () => {
    if (!history) return;
    setTimeout(() => {
        const {query} = history.location;
        const {redirect} = query as { redirect: string };
        history.push(redirect || '/');
    }, 10);
};

const Login: React.FC = () => {
    const [submitting, setSubmitting] = useState(false);
    const [userLoginState, setUserLoginState] = useState<BZAPI.LoginResult>({});
    const [type, setType] = useState<string>('account');
    const {initialState, setInitialState} = useModel('@@initialState');

    const intl = useIntl();

    const fetchUserInfo = async () => {
        // const userInfo = await initialState?.fetchUserInfo?.();
        // if (userInfo) {
        //
        // }
        setInitialState({
            ...initialState,
            currentUser: {
                name: localStorage.userName
            },
        });
    };


    const menuFormatter = (response: any) => {
        if (response === null)
            return [];
        return response.map((item: { key: string; value: string; navs: any; parentName: string }) => {
            const result = {
                routes: {},
                name: typeof item.key === "undefined" ? item.parentName : item.key,
                path: typeof item.value === "undefined" ? '' : item.value,
            };
            if (item.navs) {
                result.routes = menuFormatter(item.navs);
            }
            console.log(result);
            return result;
        })
    }

    const handleSubmit = async (values: BZAPI.LoginParams) => {
        setSubmitting(true);
        try {
            // 登录
            const msg = await adminLogin({...values});
            console.log(msg, msg.code === 0);
            if (msg.code === 0) {
                const defaultloginSuccessMessage = intl.formatMessage({
                    id: 'pages.login.success',
                    defaultMessage: 'login success！',
                });
                message.success(defaultloginSuccessMessage);
                localStorage.abcAccessToken = msg.data.accessToken;
                localStorage.userName = msg.data.userName;
                localStorage.account = msg.data.userName;
                await fetchUserInfo();
                setInitialState({
                    settings: {
                        ...defaultSettings,
                        menu: {
                            request: async () => {
                                const menuData = await getMenus();
                                let dt = [];
                                menuData.data.list.map((item) => {
                                    console.log(item);
                                    if (item.parentName === "Collection Management") {
                                        dt = item.navs;
                                    }
                                })
                                return menuFormatter(dt);
                            }
                        }
                    },
                });
                goto();
                return;
            } else {
                message.warn(msg.msg)
            }
        } catch (error) {
            const defaultloginFailureMessage = intl.formatMessage({
                id: 'pages.login.failure',
            });

            message.error(defaultloginFailureMessage);
        }
        setSubmitting(false);
    };
    const {status, type: loginType} = userLoginState;

    return (
        <div className={styles.container}>
            <div className={styles.lang} data-lang>
                {SelectLang && <SelectLang/>}
            </div>
            <div className={styles.content}>
                <div className={styles.main}>
                    <ProForm
                        initialValues={{
                            autoLogin: true,
                        }}
                        submitter={{
                            searchConfig: {
                                submitText: intl.formatMessage({
                                    id: 'pages.login.submit',
                                }),
                            },
                            render: (_, dom) => dom.pop(),
                            submitButtonProps: {
                                loading: submitting,
                                size: 'large',
                                style: {
                                    width: '100%',
                                },
                            },
                        }}
                        onFinish={async (values) => {
                            handleSubmit(values as BZAPI.LoginParams);
                        }}
                    >
                        <Tabs activeKey={type} onChange={setType}>
                            <Tabs.TabPane
                                key="account"
                                tab={intl.formatMessage({
                                    id: 'pages.login.accountLogin.tab',
                                })}
                            />
                        </Tabs>

                        {status === 'error' && loginType === 'account' && (
                            <LoginMessage
                                content={intl.formatMessage({
                                    id: 'pages.login.accountLogin.errorMessage',
                                })}
                            />
                        )}
                        {type === 'account' && (
                            <>
                                <ProFormText
                                    name="account"
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <UserOutlined className={styles.prefixIcon}/>,
                                    }}
                                    placeholder={"stuffNo"}
                                    rules={[
                                        {
                                            required: true,
                                            message: (
                                                <FormattedMessage
                                                    id="pages.login.username.required"
                                                />
                                            ),
                                        },
                                    ]}
                                />
                                <ProFormText.Password
                                    name="verifyCode"
                                    fieldProps={{
                                        size: 'large',
                                        prefix: <LockOutlined className={styles.prefixIcon}/>,
                                    }}
                                    placeholder={"password"}
                                    rules={[
                                        {
                                            required: true,
                                            message: (
                                                <FormattedMessage
                                                    id="pages.login.password.required"
                                                    defaultMessage="请输入密码！"
                                                />
                                            ),
                                        },
                                    ]}
                                />
                            </>
                        )}

                        <div
                            style={{
                                marginBottom: 24,
                            }}
                        >
                            <ProFormCheckbox noStyle name="autoLogin">
                                <FormattedMessage id="pages.login.rememberMe"/>
                            </ProFormCheckbox>
                            <a
                                style={{
                                    float: 'right',
                                }}
                            >
                            </a>
                        </div>
                    </ProForm>
                </div>
            </div>
        </div>
    );
};

export default Login;
